package edu.hnu.cloudflight.android.adapter;

import java.util.List;

import android.content.Context;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import edu.hnu.cloudflight.android.util.FlightCitiesUtil;

public class CityAdapter extends ArrayAdapter<String> implements Filterable {

	@SuppressWarnings("unused")
	private final static String TAG = CityAdapter.class.getSimpleName();

	private List<String> resultList;

	public CityAdapter(Context context, int textViewResourceId) {
		super(context, textViewResourceId);
	}

	@Override
	public int getCount() {
		return resultList.size();
	}

	@Override
	public String getItem(int index) {
		return resultList.get(index);
	}

	@Override
	public Filter getFilter() {
		Filter filter = new Filter() {
			@Override
			protected FilterResults performFiltering(CharSequence constraint) {
				FilterResults filterResults = new FilterResults();
				if (constraint != null) {
					String text = constraint.toString();
					String s = text.trim();
					char first = s.charAt(0);
					if ((first >= 'a' && first <= 'z')|| (first >= 'A' && first <= 'Z')) {
						resultList = FlightCitiesUtil.getCitiesBySpell(s);
					} else {
						resultList = FlightCitiesUtil.getCitiesByCC(s);
					}
					filterResults.values = resultList;
					filterResults.count = resultList.size();
				}
				return filterResults;
			}

			@Override
			protected void publishResults(CharSequence constraint,
					FilterResults results) {
				if (results != null && results.count > 0) {
					notifyDataSetChanged();
				} else {
					notifyDataSetInvalidated();
				}
			}
		};
		return filter;
	}
}